package com.dhcc.httpserver.configread;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.sun.org.apache.xerces.internal.xni.QName;

public class WebHandler extends DefaultHandler {

	private List<Entity> entityList;
	private List<Mapping> mappingList;
	private String tag;
	private boolean isMap;
	private Entity entity;
	private Mapping mapping;

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {

		if (null == tag) {
			return;
		}
		
		String str = new String(ch, start, length);
		str = str.trim();

		if (isMap) {

			if ("servlet-name".equals(tag)) {
				mapping.setName(str);
			} else if ("url-pattern".equals(tag)) {
				mapping.getUrlPattern().add(str);
			}

		} else {

			if ("servlet-name".equals(tag)) {
				entity.setName(str);
			} else if ("servlet-class".equals(tag)) {
				entity.setClazz(str);
			}

		}

	}

	@Override
	public void startDocument() throws SAXException {
		// 开始读取文档
		entityList = new ArrayList<Entity>();
		mappingList = new ArrayList<Mapping>();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		// 开始标签
		if (null != qName) {
			tag = qName;
		}

		if (qName.equals("servlet")) {
			isMap = false;
			entity = new Entity();
		}

		if (qName.equals("servlet-mapping")) {
			isMap = true;
			mapping = new Mapping();
		}

	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		// 开始结束
		if (null==qName) {
			
			return;
		}
		
		if (qName.equals("servlet")) {
			
			entityList.add(entity);
		}else if (qName.equals("servlet-mapping")) {
			mappingList.add(mapping);
		}
		tag=null;
		

	}

	@Override
	public void endDocument() throws SAXException {
		// 结束读取文档

	}
	
	
	
	
	
	public List<Entity> getEntityList() {
		return entityList;
	}

	public void setEntityList(List<Entity> entityList) {
		this.entityList = entityList;
	}

	public List<Mapping> getMappingList() {
		return mappingList;
	}

	public void setMappingList(List<Mapping> mappingList) {
		this.mappingList = mappingList;
	}

	public static void main(String[] args) throws Exception, SAXException {
		
		
		
	}

}
